package com.by.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.by.entity.Member;
import com.by.entity.dto.MemberRegisterDTO;
import com.by.mapper.MemberMapper;
import com.by.service.MemberService;
import lombok.experimental.Accessors;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
@Accessors(makeFinal = true)
public class MemberServiceImpl extends ServiceImpl <MemberMapper, Member> implements MemberService {

    @Autowired
    private MemberMapper memberMapper;

    @Autowired
    private PasswordEncoder passwordEncoder;


    /**
     * 会员注册
     * @param registerDTO
     * @return
     */
    @Override
    public Long register(MemberRegisterDTO registerDTO) {
        // 检查用户名是否已存在
        if (usernameExists(registerDTO.getUsername())) {
            throw new IllegalArgumentException("用户名已存在");
        }
        //密码不能为空 min = 6, max = 20, 密码长度6-20个字符
        if(registerDTO.getPassword().length()< 6 || registerDTO.getPassword().length() > 20){
            throw new IllegalArgumentException("密码长度6-20个字符");
        }
        // 确认密码不能为空
        if(registerDTO.getConfirmPassword().isEmpty()){
            throw new IllegalArgumentException("确认密码不能为空");
        }
        if(registerDTO.getConfirmPassword().length()< 6 || registerDTO.getConfirmPassword().length() > 20){
            throw new IllegalArgumentException("确认密码长度6-20个字符");
        }
        // 检查手机号是否为空 "^1[3-9]\\d{9}$", 手机号格式不正确
        if (!registerDTO.getMobile().matches("^1[3-9]\\d{9}$")) {
            throw new IllegalArgumentException("手机号格式不正确");
        }

        // 检查手机号是否已注册
        if (mobileExists(registerDTO.getMobile())) {
            throw new IllegalArgumentException("手机号已注册");
        }

        // 创建会员实体
        Member member = new Member();
        BeanUtils.copyProperties(registerDTO, member);

        // 设置必要属性
        member.setPassword(passwordEncoder.encode(registerDTO.getPassword()));
        member.setCreateTime(new Date());
        member.setUpdateTime(new Date());
        member.setDeleteFlag(false);
        member.setDisabled(false);
        member.setPoint(0);
        member.setExperience(0);
        member.setTotalPoint(0);
        member.setLastLoginDate(new Date());

        // 保存会员信息
        save(member);

        return member.getId();
    }
    // 检查用户名是否存在
    @Override
    public boolean usernameExists(String username) {
        return false;
    }
    // 检查手机号是否存在
    @Override
    public boolean mobileExists(String mobile) {
        return false;
    }

    /**
     *更新会员信息
     * @param
     * @return
     */
    public boolean updateMember(Member member) {
        return false;
    }

}
